package com.wq.httpclientcore.utils;

import com.baomidou.mybatisplus.core.conditions.ISqlSegment;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wq.httpclientcore.entities.req.query.BaseReq;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.BeanUtils;

public class QueryWrapperBuilder {

    public static <T, R> LambdaQueryWrapper<T> queryWrapper(Class<T> clazz, R r) {
        try {
            T t = clazz.newInstance();
            BeanUtils.copyProperties(r, t);

            LambdaQueryWrapper<T> lambdaQuery = Wrappers.lambdaQuery(t);
            if (r instanceof BaseReq baseReq) {
                if (StringUtils.isNotBlank(baseReq.getOrderBy())) {
                    lambdaQuery.last(baseReq.getOrderBy());
                } else if (StringUtils.isNotBlank(baseReq.getOrderByField())) {
                    String underScoreCase = CommonUtils.toUnderScoreCase(baseReq.getOrderByField());
                    ISqlSegment[] sqlSegments = {SqlKeyword.ORDER_BY, () -> underScoreCase
                            , baseReq.getOrderBySort() ? SqlKeyword.ASC : SqlKeyword.DESC};
                    lambdaQuery.getExpression().add(sqlSegments);
                }
            }
            return lambdaQuery;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
